package com.framework.base;

import com.alibaba.fastjson.JSON;
import com.framework.exception.BizException;
import com.framework.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2021/9/2 15:43
 */
@Slf4j
public class ResultBuilder {
    public ResultBuilder() {
    }

    public static <T> ResultDTO<T> success() {
        return success(null);
    }

    public static <T> ResultDTO<T> success(T data) {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setSuccess(true);
        resultDTO.setData(data);
        resultDTO.setCode(HttpStatus.OK.value()+"");
        resultDTO.setMsg(null);
        return resultDTO;
    }

    public static <T> ResultDTO<T> failure(String errCode, String errMsg) {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setSuccess(false);
        resultDTO.setCode(errCode);
        resultDTO.setMsg(errMsg);
        log.error("errInfo => " + JSON.toJSONString(resultDTO));
        return resultDTO;
    }

    public static <T> ResultDTO<T> failure(String errCode) {
        String errMsg = MessageUtil.getMessage(errCode);
        return failure(errCode, errMsg);
    }

    public static <T> ResultDTO<T> failure(Throwable t) {
        String _errCode = null;
        String _errMsg = null;
        if (t instanceof BizException) {
            BizException e = (BizException) t;
            _errCode = e.getErrorMsg().getCode();
            try {
                _errMsg = MessageUtil.getMessage(_errCode);
            }catch (Exception eee){
                log.error("MessageUtil.getMessage err, errCode:"+_errCode, eee);
            }
            if (_errMsg == null || _errMsg.trim().length() == 0) {
                _errMsg = e.getMessage();
            }
        } else {
            _errCode = "500";
            _errMsg = t.getMessage();
        }
        if (StringUtils.isBlank(_errMsg)){
            _errMsg = MessageUtil.getMessage(_errCode);
        }
        if(StringUtils.isBlank(_errCode)){
            _errCode = "500";
        }
        return failure(_errCode, _errMsg);
    }
}
